package com.softcits.email.quartz;

import org.quartz.TriggerUtils;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

public final class QuartzUtil {
    private final static Logger logger = LoggerFactory.getLogger(QuartzUtil.class);

    public static List<String> getNextExecutionTime(String cronExpression, Integer numTimes) {
        if (Objects.isNull(numTimes) || numTimes < 1) {
            return null;
        }
        List<String> list = new ArrayList<>(numTimes);
        CronTriggerImpl cronTrigger = new CronTriggerImpl();
        try {
            cronTrigger.setCronExpression(cronExpression);
            List<Date> dates = TriggerUtils.computeFireTimes(cronTrigger, null, numTimes);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
            for(Date date : dates) {
                list.add(sdf.format(date));
            }
        } catch (Exception e) {
            logger.warn("Failed to parse cron expression, reason: {}", e.getMessage());
            return null;
        }

        return list;
    }

    public static void main(String[] args) {
        List<String> runTimeList = getNextExecutionTime("0 0/30 * * * ? *", 5);
        for(String str: runTimeList) {
            logger.debug(str);
        }
    }
}
